router.get('/', async (req, res) => {
  try {
    const search = req.query.search || '';
    const publisher = req.query.publisher || '';
    const category = req.query.category || '';
    const page = parseInt(req.query.page) || 1;
    const limit = 10;
    const offset = (page - 1) * limit;

    let query = {};

    // 构建查询条件
    if (search) {
      query.$or = [
        { Title: { $regex: search, $options: 'i' } },
        { Authors: { $regex: search, $options: 'i' } },
        { Publisher: { $regex: search, $options: 'i' } }
      ];
    }

    if (publisher) {
      query.Publisher = publisher;
    }

    if (category) {
      query.Category = category;
    }

    // 获取图书总数
    const count = await Book.countDocuments(query);

    // 获取图书列表
    const books = await Book.find(query)
      .sort({ _id: -1 })
      .skip(offset)
      .limit(limit);

    // 获取出版商列表和每个出版商的图书数量
    const publisherCounts = await Book.aggregate([
      { $group: { _id: "$Publisher", count: { $sum: 1 } } },
      { $match: { _id: { $ne: null } } },
      { $sort: { count: -1 } },
      { $project: { name: "$_id", count: 1, _id: 0 } }
    ]);

    // 分页信息
    const pagination = {
      current: page,
      total: Math.ceil(count / limit),
      hasPrev: page > 1,
      hasNext: page < Math.ceil(count / limit)
    };

    console.log('Total book count:', count);

    res.render('books', {
      books,
      publisherCounts,
      pagination,
      search,
      publisher,
      category,
      count
    });
  } catch (error) {
    console.error('获取图书列表失败:', error);
    res.status(500).render('error', { message: '获取图书列表失败，请稍后重试' });
  }
}); 
